package com.xiaoyu.base.image;

import android.text.TextUtils;

import com.xiaoyu.base.utils.upload.UploadImageOriginalType;

import java.io.File;

import in.srain.cube.request.JsonData;

public class ImageLoadInfo {

    private final String originUrl;
    private int mOriginWidth = -1;
    private int mOriginHeight = -1;
    private double mRatio;
    private int mSizeKb = 0;
    private int mOriginalType = UploadImageOriginalType.COMPRESSED;

    public ImageLoadInfo(String originUrl) {
        this.originUrl = originUrl;
        if (TextUtils.isEmpty(originUrl)) {
            return;
        }
        extractImageWidthAndHeight();
        mRatio = calculateRatio();
    }

    public ImageLoadInfo(int width, int height) {
        originUrl = "";
        mOriginWidth = width;
        mOriginHeight = height;
        mRatio = calculateRatio();
    }

    public double getRatio() {
        return mRatio;
    }

    public int getSizeKb() {
        return mSizeKb;
    }

    public int getOriginalType() {
        return mOriginalType;
    }

    private double calculateRatio() {
        if (mOriginWidth <= 0 || mOriginHeight <= 0) {
            return 1d;
        }
        return mOriginWidth * 1d / mOriginHeight;
    }

    private void extractImageWidthAndHeight() {
        if (TextUtils.isEmpty(originUrl)) {
            return;
        }
        try {
            final String fileName = new File(originUrl).getName();
            if (TextUtils.isEmpty(fileName)) {
                return;
            }
            final String[] fileNameParts = fileName.split("\\.");
            if (fileNameParts.length == 0) {
                return;
            }
            final String[] parts = fileNameParts[0].split("-");
            final int len = parts.length;
            if (len < 4) {
                return;
            }
            mOriginWidth = JsonData.toInteger(parts[2], 0);
            mOriginHeight = JsonData.toInteger(parts[3], 0);
            if (len < 6) {
                return;
            }
            mSizeKb = JsonData.toInteger(parts[4], 0);
            mOriginalType = JsonData.toInteger(parts[5], UploadImageOriginalType.COMPRESSED);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
